import React from 'react';
import { Tree } from 'antd';

const { TreeNode } = Tree;

const TableTreeFilter = ({ clearFilters, confirm, filters = [], selectedKeys, setSelectedKeys, treeProps }) => {
    const wrapStyle = {
        paddingRight: 16,
        maxHeight: 180,
        overflow: 'auto'
    };

    const handleSelect = (keys, { selected, node }) => {
        const {
            props: { parentKey, fullKeys, dataRef, eventKey }
        } = node;
        let arr = [];
        let arr2 = [];
        if (dataRef?.children) {
            arr2 = dataRef?.children.map(item => item.value);
        }
        if (selected) {
            arr = selectedKeys.concat([eventKey]).concat(arr2);
        } else {
            arr = selectedKeys.filter(item => item !== eventKey && item !== parentKey && !arr2.includes(item));
        }
        if (parentKey && fullKeys && fullKeys.length > 0) {
            let flag = true;
            for (let i = 0; i < fullKeys.length; i += 1) {
                if (!arr.includes(fullKeys[i])) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                arr.push(parentKey);
            }
        }
        setSelectedKeys([...new Set(arr)]);
    };

    const handleCheck = keys => {
        setSelectedKeys(keys);
    };

    const renderTreeNodes = (data, parentKey = '', fullKeys) =>
        data.map(item => {
            if (item.children) {
                return (
                    <TreeNode title={item.text} key={item.value} dataRef={item} parentKey={parentKey}>
                        {renderTreeNodes(
                            item.children,
                            item.value,
                            item.children.map(o => o.value)
                        )}
                    </TreeNode>
                );
            }
            return (
                <TreeNode title={item.text} key={item.value} dataRef={item} parentKey={parentKey} fullKeys={fullKeys} />
            );
        });

    return (
        <>
            <div style={wrapStyle}>
                <Tree
                    checkable
                    multiple
                    onSelect={handleSelect}
                    onCheck={handleCheck}
                    selectedKeys={selectedKeys}
                    checkedKeys={selectedKeys}
                    defaultExpandAll
                    {...treeProps}
                >
                    {renderTreeNodes(filters)}
                </Tree>
            </div>
            <div className="ant-table-filter-dropdown-btns">
                <a className="ant-table-filter-dropdown-link confirm" onClick={confirm}>
                    确定
                </a>
                <a className="ant-table-filter-dropdown-link clear" onClick={clearFilters}>
                    重置
                </a>
            </div>
        </>
    );
};

export default TableTreeFilter;
